package org.basis.advance.c1;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Random;

/**
 * 按换行符分割消息测试
 *
 * @author Mr_wenpan@163.com 2021/09/20 12:11
 */
@Slf4j
public class Client3 {

    public static void main(String[] args) {
        send();
        System.out.println("finish.");
    }

    private static void send() {

        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(worker);

            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 添加入站handler
                    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                    // 连接建立完毕后批量向server发送消息
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {
                        // 在连接建立完毕后被吊起
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            ByteBuf buffer = ctx.alloc().buffer();
                            char c = '0';
                            Random random = new Random();
                            for (int i = 0; i < 10; i++) {
                                StringBuilder builder = makeString(c, random.nextInt(256) + 1);
                                c++;
                                // 写入到buffer中，但暂时不发出
                                buffer.writeBytes(builder.toString().getBytes());
                            }
                            // 批量发出消息
                            ctx.writeAndFlush(buffer);
                        }
                    });
                }
            });

            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
            channelFuture.channel().closeFuture().sync();

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }

    }

    /**
     * 组装消息，按换行符分割
     */
    public static StringBuilder makeString(char c, int len) {
        StringBuilder sb = new StringBuilder(len + 2);
        for (int i = 0; i < len; i++) {
            sb.append(c);
        }
        sb.append("\n");
        return sb;
    }
}
